<?php

namespace app\admin\controller;

use app\admin\services\QuanGuanMemberService;
use app\admin\services\StoreService;
use app\admin\services\TaskService;
use app\enums\enum\TaskSourceEnum;
use app\enums\enum\TaskTypeEnum;
use app\home\services\MemberService;
use think\App;

class TaskController extends Common implements ICurd
{

    /**
     * 任务类型
     */
    private $taskTypeList;

    private $taskSourceList;


    public function initialize()
    {
        $this->setTaskTypeList();
        $this->setTaskSourceList();
    }

    public function index()
    {
        // TODO: Implement index() method.
        if (request()->isPost()) {
            $requestData = input('post.');
            $param['page'] = $requestData['page'] ?: 1;
            $param['pageSize'] = $requestData['limit'] ?: 10;
            $param['key'] = trim($requestData['key']) ?: "";
            $param['type'] = (int)$requestData['type'] ?: 0;
            $param['source'] = (int)$requestData['source'] ?: 0;
            $param['create_id'] = (int)$requestData['create_id'] ?: 0;
            // 需要查询的字段
            $field = "
                id,
                title,
                task_target,
                status,
                create_time,
                type,
                begin_time,
                end_time,
                source,
                store_id,
                create_id
            ";
            $list = $this->getService()->list($param, $field);
            foreach ($list['data'] as &$item) {
                if ($item['source'] == 1) {
                    $item['create_id'] = "管理员";
                } else {
                    $item['create_id'] = QuanGuanMemberService::makeInstance()->getInfoById($item['create_id'])['name'] ?: '管理员';
                }
                $item['create_time'] = date("Y-m-d H:i:s", $item['create_time']);
                $item['begin_time'] = date("Y-m-d", $item['begin_time']);
                $item['end_time'] = date("Y-m-d", $item['end_time']);
                $item['type'] = TaskTypeEnum::getEnumInfo($item['type']);
                $item['source'] = TaskSourceEnum::getEnumInfo($item['source']);
                $item['store_id'] = StoreService::makeInstance()->getInfoById($item['store_id'])['title'] ?: '系统发布';
            }
            return $this->jsonList($list['data'], $list['total']);
        }
        return $this->fetch("task/index");
    }

    public function create()
    {
        // TODO: Implement create() method.
        if (request()->isPost()) {
            $param = $this->mapping();
            [$beginDate, $endDate] = getBeginDateAndEndDateByTime(time());
            // 本周开始日期和结束日期
            if ($param['type'] == 2) {
                // 下周开始日期和结束日期
                [$beginDate, $endDate] = getBeginDateAndEndDateByTime(time());
                $beginDate = addDaysBydate($beginDate, 7);
                $endDate = addDaysBydate($endDate, 7);
            }
            // 项目创建的时候，任务目标复用标题的数据
            if (!isset($param['task_target']) || empty($param['task_target'])) {
                $param['task_target'] = $param['title'];
            }
            $param['begin_time'] = strtotime($beginDate);
            $param['end_time'] = strtotime($endDate);
            $res = $this->getService()->save($param);
            if ($res) {
                return $this->jsonSuccess("index");
            }
            return $this->jsonError();
        }
        return $this->fetch("task/create");
    }

    public function update($id = 0)
    {
        // TODO: Implement update() method.
        if (request()->isPost()) {
            $param = $this->mapping();
            [$beginDate, $endDate] = getBeginDateAndEndDateByTime(time());
            // 本周开始日期和结束日期
            if ($param['type'] == 2) {
                // 下周开始日期和结束日期
                [$beginDate, $endDate] = getBeginDateAndEndDateByTime(time());
                $beginDate = addDaysBydate($beginDate, 7);
                $endDate = addDaysBydate($endDate, 7);
            }
            // 项目创建的时候，任务目标复用标题的数据
            if (!isset($param['task_target']) || empty($param['task_target'])) {
                $param['task_target'] = $param['title'];
            }
            $param['begin_time'] = strtotime($beginDate);
            $param['end_time'] = strtotime($endDate);
            $param['create_time'] = strtotime($param['create_time']);
            $res = $this->getService()->save($param, $id);
            if ($res) {
                return $this->jsonSuccess("index");
            }
            return $this->jsonError();
        } else {
            $info = $this->getService()->getInfoById($id);
            $info['begin_time'] = date("Y-m-d", $info['begin_time']);
            $info['end_time'] = date("Y-m-d", $info['end_time']);
            $info['create_time'] = date("Y-m-d H:i:s", $info['create_time']);
            $this->assign([
                'info' => json_encode($info, true),
                'infoArr' => $info,
            ]);
            return $this->fetch("task/update");
        }
        return $this->jsonError();
    }

    public function remove()
    {
        // TODO: Implement remove() method.
        if (request()->isPost()) {
            $data = input('post.');
            $id = (int)$data['id'];
            $res = $this->getService()->save(['is_delete' => 2], $id);
            if ($res) {
                return $this->jsonSuccess("index");
            }
            return $this->jsonError();
        }
        return $this->jsonError();
    }

    public function detail()
    {
        // TODO: Implement detail() method.
    }

    public function setStatus()
    {
        // TODO: Implement setStatus() method.
        if (request()->isPost()) {
            $id = input('post.id', 0, 'int');
            $status = input('post.status', 0, 'int');
            $res = $this->getService()->save([
                'status' => $status
            ], $id);
            if ($res) {
                return $this->jsonSuccess('index');
            }
            return $this->jsonError();
        }
        return $this->jsonError();
    }

    private function getService()
    {
        return TaskService::makeInstance();
    }

    private function mapping()
    {
        $data = input('post.');
        $param = [
            'title' => trim($data['title']) ?: "",
            'describe' => trim($data['describe']) ?: "",
            'create_time' => trim($data['create_time']) ?: "",
            'status' => (int)$data['status'] ?: 1,
            'type' => (int)$data['type'] ?: 1,
            'sort' => (int)$data['sort'] ?: 0
        ];
        return $param;
    }

    private function setTaskTypeList()
    {
        $this->taskTypeList = TaskTypeEnum::getEnumList();
        $this->assign([
            'taskTypeList' => $this->taskTypeList
        ]);
    }

    private function setTaskSourceList()
    {
        $this->taskSourceList = TaskSourceEnum::getEnumList();
        $this->assign([
            'taskSourceList' => $this->taskSourceList
        ]);
    }

}